package com.miracle.system.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.miracle.common.utils.SecurityUtils;
import com.miracle.common.utils.ServletUtils;
import com.miracle.common.utils.VerifyCodeUtils;
import com.miracle.core.redis.RedisCache;
import com.miracle.core.security.domain.SecurityUserDetails;
import com.miracle.core.security.service.TokenService;
import com.miracle.system.base.domain.ResultMap;
import com.miracle.system.domain.SysResource;
import com.miracle.system.domain.SysUser;
import com.miracle.system.service.SysResourceService;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.miracle.common.constant.Constants;
import com.miracle.core.security.domain.SecurityBody;
import com.miracle.system.service.SysLoginService;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录验证
 *
 * @author miracle
 */
@ApiModel(value = "登陆类")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;
    @Autowired
    TokenService tokenService;
    @Autowired
    SysResourceService resourceService;
    @Autowired
    RedisCache redisCache;
    /**
     * 登录方法
     *
     * @return 结果
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody SecurityBody securityBody)
    {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 生成令牌
        String token = loginService.login(securityBody.getUsername(), securityBody.getPassword(), securityBody.getCode(), securityBody.getUuid());
        resultMap.put(Constants.TOKEN, token);
        resultMap.put("code", 200);
        return resultMap;
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Map<String, Object> getInfo()
    {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        SecurityUserDetails userDetails = tokenService.getUserDetails(ServletUtils.getRequest());
        SysUser user = userDetails.getUser();
        // 角色集合
        //List<String> roles = resourceService.getRolePermission(user);
        // 权限集合
        List<String> permissions = resourceService.selectPermissionListByUser(user);
        resultMap.put("code", 200);
        resultMap.put("msg", "123");
        resultMap.put("user", user);
        resultMap.put("roles", "roles");
        resultMap.put("permissions", permissions);
        return resultMap;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public ResultMap getRouters()
    {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        List<SysResource> resources = resourceService.selectResourceByUserId(SecurityUtils.getUserId());
        return ResultMap.success(resourceService.buildResources(resources));
    }

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Map<String, Object> getCode(HttpServletResponse response) throws IOException
    {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            resultMap.put("code", 200);
            resultMap.put("uuid", uuid);
            resultMap.put("img", Base64.encode(stream.toByteArray()));
            return resultMap;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            resultMap.put("msg", e.getMessage());
            resultMap.put("code", 500);
            return resultMap;
        }
        finally
        {
            stream.close();
        }
    }
}
